<script setup lang="ts">
  import { createVNode, onMounted, ref, watch } from 'vue'
  import { message, Modal } from 'ant-design-vue'
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
  import {
    deletePermissionReq,
    deleteRoleReq,
    frozenUserReq,
    getPermissionListReq,
    getRoleListReq,
    getUsersReq,
  } from '@/api'
  import { useSearchStore } from '@/store/search'
  import { storeToRefs } from 'pinia'
  import { userColumns, roleColumns, permissionColumns } from './columns'
  import CreateRole from './CreateRole.vue'
  import CreatePermission from './CreatePermission.vue'
  import EditRole from './EditRole.vue'
  import EditPermission from './EditPermission.vue'
  import EditUserRole from './EditUserRole.vue'
  import usePagination from '@/hooks/usePagination'
  const searchStore = useSearchStore()
  const { searchValue } = storeToRefs(searchStore)

  const selectOptions = [
    { id: 0, name: '用户', value: 'user' },
    { id: 1, name: '角色', value: 'roles' },
    { id: 3, name: '权限', value: 'permissions' },
  ]

  // 列表数据
  const dataSource = ref<any[]>([])

  const selectOption = ref('user')

  // 选择-用户、角色、权限
  const optionChange = (value: string) => {
    selectOption.value = value
    dataSource.value =
      value === 'user'
        ? userList.value
        : value === 'roles'
          ? roleList.value
          : permissionList.value
  }

  // 编辑用户角色
  const showEditUserRole = ref(false)
  const editUserRoleRecord = ref(null)

  // 编辑用户角色-确认
  const handleEditUserRoleOk = () => {
    showEditUserRole.value = false
  }

  // 编辑用户角色
  const editUserRoleFun = (record: any) => {
    editUserRoleRecord.value = record
    showEditUserRole.value = true
  }

  // 添加和编辑角色
  const showCreate = ref(false)
  const showEdit = ref(false)
  const editRecord = ref(null)

  // 添加-角色、权限
  const handleCreateOk = () => {
    showCreate.value = false
  }

  // 编辑-角色、权限-确认
  const handleEditOk = () => {
    showEdit.value = false
  }

  // 编辑-角色、权限
  const editRecordFun = (record: any) => {
    editRecord.value = record
    showEdit.value = true
  }

  // 删除-角色、权限
  const deleteRecordFun = async (record: any) => {
    Modal.confirm({
      title: `确认删除 ${selectOptions.find((item) => item.value === selectOption.value)?.name} "${record.name}" 吗？`,
      icon: createVNode(ExclamationCircleOutlined),
      content: '如果确认删除请点击确认按钮',
      async onOk() {
        try {
          if (selectOption.value === 'roles') {
            const res = await deleteRoleReq({ id: record.id })
            if (res?.data) {
              message.success('角色删除成功')
              await getRoleListFun()
              dataSource.value = roleList.value
            } else {
              message.error('角色删除失败')
            }
          } else if (selectOption.value === 'permissions') {
            const res = await deletePermissionReq({ id: record.id })
            if (res?.data) {
              message.success('权限删除成功')
              await getPermissionListFun()
              dataSource.value = permissionList.value
            } else {
              message.error('权限删除失败')
            }
          }
        } catch (error) {}
      },
      onCancel() {},
    })
  }

  // 搜索-用户名、角色名、权限名
  watch(searchValue, () => {
    if (searchValue.value) {
      const name =
        selectOption.value === 'user'
          ? 'username'
          : selectOption.value === 'roles'
            ? 'name'
            : 'code'
      dataSource.value = dataSource.value.filter((item) => {
        return item[name].includes(searchValue.value)
      })
    } else {
      dataSource.value =
        selectOption.value === 'user'
          ? userList.value
          : selectOption.value === 'roles'
            ? roleList.value
            : permissionList.value
    }
  })

  // 用户列表
  const userList = ref<any[]>([])

  // 获取用户数据
  const getUserListFun = async () => {
    try {
      const res = await getUsersReq()
      if (res?.data) {
        userList.value = res.data
        dataSource.value = res.data
      }
    } catch (error) {}
  }

  const roleList = ref<any[]>([])
  const getRoleListFun = async () => {
    const res = await getRoleListReq()
    if (res?.data) {
      roleList.value = res.data
    }
  }

  const permissionList = ref<any[]>([])
  const getPermissionListFun = async () => {
    const res = await getPermissionListReq()
    if (res?.data) {
      permissionList.value = res.data
    }
  }

  onMounted(() => {
    getUserListFun()
    getRoleListFun()
    getPermissionListFun()
  })

  // 添加成功后更新数据
  watch(showCreate, async (val, oldVal) => {
    if (oldVal && !val) {
      if (selectOption.value === 'roles') {
        await getRoleListFun()
        dataSource.value = roleList.value
      } else if (selectOption.value === 'permissions') {
        await getPermissionListFun()
        dataSource.value = permissionList.value
      } else {
        await getUserListFun()
        dataSource.value = userList.value
      }
    }
  })

  watch(showEdit, async (val, oldVal) => {
    if (oldVal && !val) {
      if (selectOption.value === 'roles') {
        await getRoleListFun()
        dataSource.value = roleList.value
      } else if (selectOption.value === 'permissions') {
        await getPermissionListFun()
        dataSource.value = permissionList.value
      } else {
        await getUserListFun()
        dataSource.value = userList.value
      }
    }
  })

  watch(showEditUserRole, (value) => {
    if (!value) {
      getUserListFun()
    }
  })

  // 为每个用户管理独立的 loading 状态
  const userLoadingMap = ref<Map<string, boolean>>(new Map())

  const frozenBeforeChange = (checked: boolean, record: any) => {
    record.isFrozen = !checked
    // 冻结用户
    const messageStr = checked ? '冻结' : '解冻'
    // 设置当前用户的 loading 状态
    userLoadingMap.value.set(record.id, true)

    Modal.confirm({
      title: `确认 "${messageStr}" 该用户吗？`,
      icon: createVNode(ExclamationCircleOutlined),
      content: '如果确认请点击确认按钮',
      async onOk() {
        try {
          const res = await frozenUserReq({ isFrozen: checked })
          if (res?.data) {
            message.success(res?.data)
            // 方案1: 立即更新本地状态（快速响应）
            record.isFrozen = checked

            // 方案2: 重新获取用户列表（确保数据一致性，可选）
            // await getUserListFun()
          }
        } catch (error) {
          message.error('操作失败，请重试')
        } finally {
          // 清除当前用户的 loading 状态
          userLoadingMap.value.set(record.id, false)
        }
      },
      onCancel() {
        // 取消时也要清除 loading 状态
        userLoadingMap.value.set(record.id, false)
      },
    })
  }
  // 获取指定用户的 loading 状态
  const getUserLoading = (userId: string) => {
    return userLoadingMap.value.get(userId) || false
  }

  const { pagination } = usePagination()
</script>

<template>
  <a-row class="top-row">
    <a-select
      ref="select"
      v-model:value="selectOption"
      style="width: 120px"
      @change="optionChange"
    >
      <a-select-option
        :value="item.value"
        v-for="item in selectOptions"
        :key="item.id"
        >{{ item.name }}
      </a-select-option>
    </a-select>
    <a-button
      class="headerButton"
      v-if="selectOption !== 'user'"
      @click="showCreate = true"
      >添加{{ selectOptions.find((item) => item.value === selectOption)?.name }}
    </a-button>
  </a-row>
  <a-table
    :columns="
      selectOption === 'user'
        ? userColumns
        : selectOption === 'roles'
          ? roleColumns
          : permissionColumns
    "
    :pagination="pagination"
    :data-source="dataSource"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'operation'">
        <a
          class="tableAction"
          @click="editRecordFun(record)"
          >编辑</a
        >
        <a
          class="tableAction"
          @click="deleteRecordFun(record)"
          >删除</a
        >
      </template>
      <template v-if="column.key === 'isFrozen'">
        <a-switch
          v-model:checked="record.isFrozen"
          :loading="getUserLoading(record.id)"
          @click="(checked: boolean) => frozenBeforeChange(checked, record)"
        />
      </template>
      <template v-if="column.key === 'username'">
        <h5>{{ record.username }}</h5>
      </template>
      <template v-if="column.key === 'name'">
        <h5>{{ record.name }}</h5>
      </template>
      <template v-if="column.key === 'code'">
        <h5>{{ record.code }}</h5>
      </template>
      <template v-if="column.key === 'permissions'">
        {{ record.permissions }}
      </template>
      <template v-if="column.key === 'userRoles'">
        <PlusOutlined
          style="margin-right: 4px; color: var(--color-blue); cursor: pointer"
          @click="editUserRoleFun(record)"
        />
        {{ record.roles }}
      </template>
    </template>
  </a-table>
  <a-modal
    v-model:open="showCreate"
    :title="
      '添加' + selectOptions.find((item) => item.value === selectOption)?.name
    "
    @ok="handleCreateOk"
    width="600px"
    :footer="null"
    destroyOnClose
  >
    <CreateRole
      v-model="showCreate"
      v-if="selectOption === 'roles'"
    />
    <CreatePermission
      v-model="showCreate"
      v-if="selectOption === 'permissions'"
    />
  </a-modal>

  <a-modal
    v-model:open="showEdit"
    :title="
      '编辑' + selectOptions.find((item) => item.value === selectOption)?.name
    "
    @ok="handleEditOk"
    width="600px"
    :footer="null"
    destroyOnClose
  >
    <EditRole
      v-model="showEdit"
      :record="editRecord"
      :permissionList="permissionList"
      v-if="selectOption === 'roles'"
    />
    <EditPermission
      v-model="showEdit"
      :record="editRecord"
      v-if="selectOption === 'permissions'"
    />
  </a-modal>

  <a-modal
    v-model:open="showEditUserRole"
    title="编辑用户角色"
    @ok="handleEditUserRoleOk"
    width="600px"
    :footer="null"
    destroyOnClose
  >
    <EditUserRole
      v-model="showEditUserRole"
      :record="editUserRoleRecord"
      :roleList="roleList"
    />
  </a-modal>
</template>

<style scoped lang="less">
  .top-row {
    margin: 16px 0;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .headerButton {
      background-color: var(--color-blue);
      color: white;
      font-size: 12px;
    }
  }

  .tableAction {
    margin-right: 8px;
    cursor: pointer;
  }
</style>
